<?php
class adModel extends CI_Model {

	 public function insert_new_ad($data)
    {       
       $this->db->insert('ads',$data); 
       return; 
    }

    public function get_records($tot_num, $offset, $sort_by, $sort_order, $cat)
    {
      $this->db->order_by($sort_by, $sort_order);

      if($cat != -1)
      {
          $this->db->where('ads.cat_id', $cat);
      }
    
        
      //user data
      $this->db->join('user','user.user_id=ads.user_id');
      //cat data
      $this->db->join('category','category.cat_id=ads.cat_id');

      $this->db->where('ads.active', '1');
      $query = $this->db->get('ads', $tot_num, $offset);
      $ret['records'] = $query->result();



      //for total num rows
      if($cat != -1)
      {
          $this->db->where('ads.cat_id',$cat);
      }
      $this->db->order_by($sort_by, $sort_order);

      $this->db->where('ads.active', '1');

      $ret['num_rows'] = $this->db->get('ads')->num_rows(); 
      return $ret;
    }	

    public function search($tot_num, $offset, $sort_by, $sort_order, $search_q)
    {
      $this->db->order_by($sort_by, $sort_order);

      $this->db->where('ads.active', '1');
      
      
      $this->db->like('ad_title', $search_q);
      //tokenize
      $token = explode ( "%20" , $search_q );
      foreach($token as $keyword)
      {
        $this->db->or_like('ad_title', $keyword);
        $this->db->or_like('keywords', $keyword);
        $this->db->or_like('disc', $keyword);  
      }
        
      //user data
      $this->db->join('user','user.user_id=ads.user_id');
      //cat data
      $this->db->join('category','category.cat_id=ads.cat_id');

      $query = $this->db->get('ads', $tot_num, $offset);
      $ret['records'] = $query->result();



      //for total num rows
      $this->db->order_by($sort_by, $sort_order);
      $this->db->where('ads.active', '1');

      $this->db->like('ad_title', $search_q);
      

      //tokenize
      $token = explode ( "%20" , $search_q );
      foreach($token as $keyword)
      {
        $this->db->or_like('ad_title', $keyword);
        $this->db->or_like('keywords', $keyword);
        $this->db->or_like('disc', $keyword);  
      }
      
      
      $ret['num_rows'] = $this->db->get('ads')->num_rows(); 
      return $ret;
    }

   
    public function get_categories() 
    {
      return $this->db->get('category')->result();
    }

    public function get_category_name($id) 
    {
      if($id ==-1)
        return "All Categories";
      else{
           $this->db->where('cat_id',$id);
            return $this->db->get('category')->result()[0]->cat_name;
      }
     
    }


}